<template>
  <el-select :loading="loading" :value="valueModel" :size="size"
             :clearable="props.clearable" :placeholder="props.placeholder"
             v-model="valueModel"
             :popper-options="popper_options">
    <el-option v-if="props.selectAll" label="- 查询全部 -" value=""></el-option>
    <el-option v-for="item in opts" :key="item.value"
               :label="item.label" :value="item.value"></el-option>
  </el-select>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue';
import {UseDictionary, useDictionary} from "@/widget/use/use-dictionary";
import Dictionary, {DictionaryItem} from "@/lang/dict/dictionary";
import setting from "@/widget/provider/setting";
import {usePopperOptions} from "@/widget/use/use-popper-options";

/**
 * 下拉框
 */
interface Props extends /* @vue-ignore */ UseDictionary {
    /** model-value */
    modelValue?: boolean | number | string
    /** 组件大小 */
    size?: string
    /** 输入框的占位文字提示 */
    placeholder?: string

    /** 是否显示清除按钮 */
    clearable?: boolean
    /** 是否显示"选中全部"选项 */
    selectAll?: boolean


    /** 数据字典配置 */
    options?: DictionaryItem[] | string
    /** 异步查询参数 */
    where?: Record<string, any>
    /** 异步获取字典数据的函数 */
    provider?:  (options: string | Record<string, any> | DictionaryItem[]) => Promise<Dictionary>
}

// 使用 withDefaults 设置默认值
const props = withDefaults(defineProps<Props>(), {
    size: 'default',
    placeholder: '',
    clearable: true,
    selectAll: false
})

// 弹窗配置，没这玩意儿会报错
const popper_options = usePopperOptions();

// Emits
const emit = defineEmits(['update:modelValue', 'change']);

// 定义要触发的事件，用于更新 v-model 的值
const valueModel = computed({
    get() {
        return props.modelValue;
    },
    set: val =>{
        emit('update:modelValue', val);
        emit('change', val);
    }
});


const {opts, loading} = useDictionary(props);

</script>